Load needed libraries
library(fastDummies)
library(readr)
library(ggplot2)
library(dplyr)
library(caret)
library(glmnet)
library(boot)
library(tree)
library(ranger)
library(xgboost)
library(gbm)
library(vip)
library(ISLR)
Set the seed for reproducibility
set.seed(1)
Load the dataset
original_lc_data <- read.csv("LCdata.csv",sep = ";")
lc_data <- original_lc_data
remove attributes not available for prediction
lc_data <- subset(lc_data, select = -c(collection_recovery_fee, installment, issue_d,
last_pymnt_amnt, last_pymnt_d, loan_status,
next_pymnt_d, out_prncp, out_prncp_inv,
pymnt_plan, recoveries, total_pymnt,
total_pymnt_inv,total_rec_int, total_rec_late_fee, total_rec_prncp))
summary(lc_data)
id member_id loan_amnt funded_amnt funded_amnt_inv
Min. : 54734 Min. : 70473 Min. : 500 Min. : 500 Min. : 0
1st Qu.: 9207230 1st Qu.:10877939 1st Qu.: 8000 1st Qu.: 8000 1st Qu.: 8000
Median :34433372 Median :37095300 Median :13000 Median :13000 Median :13000
Mean :32463636 Mean :35000265 Mean :14754 Mean :14741 Mean :14702
3rd Qu.:54900100 3rd Qu.:58470266 3rd Qu.:20000 3rd Qu.:20000 3rd Qu.:20000
Max. :68617057 Max. :73544841 Max. :35000 Max. :35000 Max. :35000
term int_rate emp_title emp_length home_ownership
Length:798641 Min. : 5.32 Length:798641 Length:798641 Length:798641
Class :character 1st Qu.: 9.99 Class :character Class :character Class :character
Mode :character Median :12.99 Mode :character Mode :character Mode :character
Mean :13.24
3rd Qu.:16.20
Max. :28.99
annual_inc verification_status url desc purpose
Min. : 0 Length:798641 Length:798641 Length:798641 Length:798641
1st Qu.: 45000 Class :character Class :character Class :character Class :character
Median : 65000 Mode :character Mode :character Mode :character Mode :character
Mean : 75014
3rd Qu.: 90000
Max. :9500000
NA's :4
title zip_code addr_state dti delinq_2yrs
Length:798641 Length:798641 Length:798641 Min. : 0.00 Min. : 0.0000
Class :character Class :character Class :character 1st Qu.: 11.91 1st Qu.: 0.0000
Mode :character Mode :character Mode :character Median : 17.66 Median : 0.0000
Mean : 18.16 Mean : 0.3145
3rd Qu.: 23.95 3rd Qu.: 0.0000
Max. :9999.00 Max. :39.0000
NA's :25
earliest_cr_line inq_last_6mths mths_since_last_delinq mths_since_last_record
Length:798641 Min. : 0.0000 Min. : 0.0 Min. : 0.0
Class :character 1st Qu.: 0.0000 1st Qu.: 15.0 1st Qu.: 51.0
Mode :character Median : 0.0000 Median : 31.0 Median : 70.0
Mean : 0.6947 Mean : 34.1 Mean : 70.1
3rd Qu.: 1.0000 3rd Qu.: 50.0 3rd Qu.: 92.0
Max. :33.0000 Max. :188.0 Max. :129.0
NA's :25 NA's :408818 NA's :675190
open_acc pub_rec revol_bal revol_util total_acc
Min. : 0.00 Min. : 0.0000 Min. : 0 Min. : 0.00 Min. : 1.00
1st Qu.: 8.00 1st Qu.: 0.0000 1st Qu.: 6443 1st Qu.: 37.70 1st Qu.: 17.00
Median :11.00 Median : 0.0000 Median : 11876 Median : 56.00 Median : 24.00
Mean :11.55 Mean : 0.1953 Mean : 16930 Mean : 55.05 Mean : 25.27
3rd Qu.:14.00 3rd Qu.: 0.0000 3rd Qu.: 20839 3rd Qu.: 73.50 3rd Qu.: 32.00
Max. :90.00 Max. :63.0000 Max. :2904836 Max. :892.30 Max. :169.00
NA's :25 NA's :25 NA's :2 NA's :454 NA's :25
initial_list_status last_credit_pull_d collections_12_mths_ex_med mths_since_last_major_derog
Length:798641 Length:798641 Min. : 0.00000 Min. : 0.0
Class :character Class :character 1st Qu.: 0.00000 1st Qu.: 27.0
Mode :character Mode :character Median : 0.00000 Median : 44.0
Mean : 0.01447 Mean : 44.1
3rd Qu.: 0.00000 3rd Qu.: 61.0
Max. :20.00000 Max. :188.0
NA's :126 NA's :599107
policy_code application_type annual_inc_joint dti_joint verification_status_joint
Min. :1 Length:798641 Min. : 17950 Min. : 3.0 Length:798641
1st Qu.:1 Class :character 1st Qu.: 76167 1st Qu.:13.3 Class :character
Median :1 Mode :character Median :101886 Median :17.7 Mode :character
Mean :1 Mean :110745 Mean :18.4
3rd Qu.:1 3rd Qu.:133000 3rd Qu.:22.6
Max. :1 Max. :500000 Max. :43.9
NA's :798181 NA's :798183
acc_now_delinq tot_coll_amt tot_cur_bal open_acc_6m open_il_6m
Min. : 0.000000 Min. : 0 Min. : 0 Min. : 0.0 Min. : 0.0
1st Qu.: 0.000000 1st Qu.: 0 1st Qu.: 29861 1st Qu.: 0.0 1st Qu.: 1.0
Median : 0.000000 Median : 0 Median : 80647 Median : 1.0 Median : 2.0
Mean : 0.005026 Mean : 228 Mean : 139508 Mean : 1.1 Mean : 2.9
3rd Qu.: 0.000000 3rd Qu.: 0 3rd Qu.: 208229 3rd Qu.: 2.0 3rd Qu.: 4.0
Max. :14.000000 Max. :9152545 Max. :8000078 Max. :14.0 Max. :33.0
NA's :25 NA's :63276 NA's :63276 NA's :779525 NA's :779525
open_il_12m open_il_24m mths_since_rcnt_il total_bal_il il_util
Min. : 0.0 Min. : 0.0 Min. : 0.0 Min. : 0 Min. : 0.0
1st Qu.: 0.0 1st Qu.: 0.0 1st Qu.: 6.0 1st Qu.: 10164 1st Qu.: 58.4
Median : 0.0 Median : 1.0 Median : 12.0 Median : 24544 Median : 74.8
Mean : 0.8 Mean : 1.7 Mean : 21.1 Mean : 36428 Mean : 71.5
3rd Qu.: 1.0 3rd Qu.: 2.0 3rd Qu.: 23.0 3rd Qu.: 47640 3rd Qu.: 87.7
Max. :12.0 Max. :19.0 Max. :363.0 Max. :878459 Max. :223.3
NA's :779525 NA's :779525 NA's :780030 NA's :779525 NA's :782007
open_rv_12m open_rv_24m max_bal_bc all_util total_rev_hi_lim
Min. : 0.0 Min. : 0 Min. : 0 Min. : 0.0 Min. : 0
1st Qu.: 0.0 1st Qu.: 1 1st Qu.: 2406 1st Qu.: 47.6 1st Qu.: 13900
Median : 1.0 Median : 2 Median : 4502 Median : 61.9 Median : 23700
Mean : 1.4 Mean : 3 Mean : 5878 Mean : 60.8 Mean : 32093
3rd Qu.: 2.0 3rd Qu.: 4 3rd Qu.: 7774 3rd Qu.: 75.2 3rd Qu.: 39800
Max. :22.0 Max. :43 Max. :83047 Max. :151.4 Max. :9999999
NA's :779525 NA's :779525 NA's :779525 NA's :779525 NA's :63276
inq_fi total_cu_tl inq_last_12m
Min. : 0.0 Min. : 0.0 Min. :-4
1st Qu.: 0.0 1st Qu.: 0.0 1st Qu.: 0
Median : 0.0 Median : 0.0 Median : 2
Mean : 0.9 Mean : 1.5 Mean : 2
3rd Qu.: 1.0 3rd Qu.: 2.0 3rd Qu.: 3
Max. :16.0 Max. :35.0 Max. :32
NA's :779525 NA's :779525 NA's :779525
First we delete the columns which aren’t useful for our prediction
lc_data$id <- NULL
lc_data$member_id <- NULL
lc_data$zip_code <- NULL
lc_data$url <- NULL
Looks like policy_code contains just value equal to 1, it can be removed
lc_data$policy_code <- NULL
Remove additional columns which are related to the historical data
lc_data$last_credit_pull_d <- NULL
Then we delete the columns which can’t be converted to categorical and require NLP
lc_data$title <- NULL
lc_data$desc <- NULL
lc_data$emp_title <- NULL
let’s examine the loan_amnt column
sum(is.na(lc_data$loan_amnt))
[1] 0
cor(lc_data$loan_amnt, lc_data$int_rate)
[1] 0.1447189
hist(lc_data$loan_amnt, breaks = 20, main = "loan_amnt distribution", xlab = "loan_amnt", col = "lightblue", border = "black")
ggplot(data = lc_data, mapping = aes(x=int_rate,y=loan_amnt)) + geom_boxplot()
standardize loan_amnt
#lc_data$loan_amnt <- scale(lc_data$loan_amnt)
let’s examine the funded_amnt column
sum(is.na(lc_data$funded_amnt))
[1] 0
cor(lc_data$funded_amnt, lc_data$int_rate)
[1] 0.1448634
hist(lc_data$funded_amnt, breaks = 20, main = "funded_amnt distribution", xlab = "funded_amnt", col = "lightblue", border = "black")
as we can see, funded_amnt is almost the same as the loan_amnt column, consequently, we remove it.
lc_data$funded_amnt <- NULL
let’s examine the funded_amnt_inv column
sum(is.na(lc_data$funded_amnt_inv))
[1] 0
cor(lc_data$funded_amnt_inv, lc_data$int_rate)
[1] 0.1449083
hist(lc_data$funded_amnt_inv, breaks = 20, main = "funded_amnt_inv distribution", xlab = "funded_amnt_inv", col = "lightblue", border = "black")
remove funded_amnt_inv for the same reason as above
lc_data$funded_amnt_inv <- NULL
let’s see the int_rate distribution.
hist(lc_data$int_rate, breaks = 20, main = "int_rate distribution", xlab = "int_rate", col = "lightblue", border = "black")
Standardize int rate:
#lc_data$int_rate <- scale(lc_data$int_rate)
we delete the emp_title column as there are several entries for the same job title and because there are too many different values for one-hot encoding. In addition, some titles are unclear (NLP required)
n_distinct(lc_data$emp_title)
[1] 0
As we can observe, there are 40363 NAs. We can assume 40363 do not work.
barplot(table(lc_data$emp_length),
xlab = "emp_length years",
ylab = "Frequency",
col = "skyblue",
border = "black",
cex.names = 0.6) # The size of the main title
Since emp_length seems to be categorical, we transform it to as a factor and then as numeric. The conversion to numeric is needed for supporting the XGBoost
lc_data$emp_length <- as.factor(lc_data$emp_length)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=emp_length)) + geom_boxplot()
lc_data$emp_length <- as.numeric(lc_data$emp_length)
term
lc_data$term <- as.factor(lc_data$term)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=term)) + geom_boxplot()
lc_data$term <- as.numeric(lc_data$term)
boh = order(lc_data$term)
Cleaning of home_ownership:
During the data cleaning phase, our analysis revealed that the variable “home_ownership” does not show a distinct correlation with interest rates. Specifically, among the categories, “ANY” and “OTHER” contain 2 and 154 cases, respectively, while the “NONE” category comprises 39 cases. Although the “NONE” category appears to demonstrate a higher interest rate compared to others, the limited sample size of 39 cases raises doubts about the reliability of this observation. Notably, the “NONE” category might pertain to individuals experiencing homelessness, prompting ethical concerns about loan provision to this demographic.
table(lc_data$home_ownership)
ANY MORTGAGE NONE OTHER OWN RENT
2 399151 45 155 78789 320499
ggplot(data = lc_data, mapping = aes(x=int_rate,y=home_ownership)) + geom_boxplot()
Then, we retain mortgage, own and rent:
lc_data <- lc_data %>% filter(home_ownership %in% c("MORTGAGE","OWN","RENT"))
lc_data$home_ownership <- as.numeric(as.factor(lc_data$home_ownership))
# merging annual income
lc_data <- lc_data %>% mutate(
annual_inc_merged = ifelse(is.na(annual_inc_joint)== TRUE, annual_inc,annual_inc_joint))
lc_data <- lc_data %>% select(-annual_inc,-annual_inc_joint)
# merging debt to income ratio
lc_data <- lc_data %>% mutate(
dti_merged = ifelse(is.na(dti_joint)== TRUE, dti,dti_joint))
lc_data <- lc_data %>% select(-dti,-dti_joint)
Upon reviewing the summary again, it becomes apparent that there are merely 460 joint applications, constituting a small subset within the extensive dataset of around 800k rows. Through consolidating the debt-to-income ratios (dti’s), we can pinpoint the data pertinent to our research objectives. Hence, it is advisable to eliminate the columns verification_status_joint and application_type to prevent introducing unwarranted variability into our analysis.
table(lc_data$verification_status)
Not Verified Source Verified Verified
240255 296631 261553
table(lc_data$verification_status_joint)
Not Verified Source Verified Verified
797979 253 53 154
lc_data$verification_status <- as.numeric(as.factor(lc_data$verification_status))
lc_data <- lc_data %>% select(-verification_status_joint, -application_type)
Let’s checl if other is NA or a real value for purpose. It’s a real one, so we don’t have to handle it.
lc_data$purpose <- as.factor(lc_data$purpose)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=purpose)) + geom_boxplot()
lc_data$purpose <- as.numeric(lc_data$purpose)
Let’s have a glance to the state address:
table(lc_data$addr_state)
AK AL AR AZ CA CO CT DC DE FL GA HI IA
1992 10101 5953 18359 116578 16934 12154 2188 2268 54819 26146 4112 13
ID IL IN KS KY LA MA MD ME MI MN MO MS
11 31880 12393 7105 7726 9498 18546 18906 469 20678 14306 12821 3455
MT NC ND NE NH NJ NM NV NY OH OK OR PA
2286 22135 431 1064 3865 29991 4428 11155 66790 26682 7266 9806 28221
RI SC SD TN TX UT VA VT WA WI WV WY
3499 9609 1615 11618 63982 5629 23616 1606 17470 10446 3977 1841
lc_data$addr_state <- as.factor(lc_data$addr_state)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=addr_state)) + geom_boxplot()
lc_data$addr_state <- as.numeric(lc_data$addr_state)
Regarding delinquency in the last 2 years, there are few NAs then remove them:
lc_data <- lc_data %>%
filter(!(is.na(delinq_2yrs)))
lc_data <- lc_data %>%
mutate(mths_since_delinq_cat = ifelse(
is.na(mths_since_last_delinq) == TRUE,
"NONE",
ifelse(
mths_since_last_delinq <= 12,
"Less_1_Y",
ifelse(
mths_since_last_delinq <= 24,
"Less_2_Y",
ifelse(
mths_since_last_delinq <= 36,
"Less_3_Y",
ifelse(mths_since_last_delinq <= 48, "Less_4_Y", "More_4_Y")
)
)
)
)) %>% select(-mths_since_last_delinq)
lc_data$mths_since_delinq_cat <- as.factor(lc_data$mths_since_delinq_cat)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=mths_since_delinq_cat))+geom_boxplot()
lc_data$mths_since_delinq_cat <- as.numeric(lc_data$mths_since_delinq_cat)
lc_data <- lc_data %>%
mutate(mths_since_last_record_cat = ifelse(
is.na(mths_since_last_record) == TRUE,
"NONE",
ifelse(
mths_since_last_record <= 12,
"Less_1_Y",
ifelse(
mths_since_last_record <= 24,
"Less_2_Y",
ifelse(
mths_since_last_record <= 36,
"Less_3_Y",
ifelse(mths_since_last_record <= 48, "Less_4_Y", "More_4_Y")
)
)
)
)) %>% select(-mths_since_last_record)
lc_data$mths_since_last_record_cat <- as.factor(lc_data$mths_since_last_record_cat)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=mths_since_last_record_cat))+geom_boxplot()
lc_data$mths_since_last_record_cat <- as.numeric(lc_data$mths_since_last_record_cat)
lc_data <-lc_data %>%
mutate(mths_since_last_major_derog_cat = ifelse(
is.na(mths_since_last_major_derog) == TRUE,
"NONE",
ifelse(
mths_since_last_major_derog <= 12,
"Less_1_Y",
ifelse(
mths_since_last_major_derog <= 24,
"Less_2_Y",
ifelse(
mths_since_last_major_derog <= 36,
"Less_3_Y",
ifelse(mths_since_last_major_derog <= 48, "Less_4_Y", "More_4_Y")
)
)
)
)) %>% select(-mths_since_last_major_derog)
lc_data$mths_since_last_major_derog_cat <- as.factor(lc_data$mths_since_last_major_derog_cat)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=mths_since_last_major_derog_cat))+geom_boxplot()
lc_data$mths_since_last_major_derog_cat <- as.numeric(lc_data$mths_since_last_major_derog_cat)
lc_data$initial_list_status <- as.factor(lc_data$initial_list_status)
ggplot(data = lc_data, mapping = aes(x=int_rate,y=initial_list_status))+geom_boxplot()
lc_data$initial_list_status <- as.numeric(lc_data$initial_list_status)
Let’s check which columns still have null values
colSums(is.na(lc_data))
loan_amnt term int_rate
0 0 0
emp_length home_ownership verification_status
0 0 0
purpose addr_state delinq_2yrs
0 0 0
earliest_cr_line inq_last_6mths open_acc
0 0 0
pub_rec revol_bal revol_util
0 2 428
total_acc initial_list_status collections_12_mths_ex_med
0 0 99
acc_now_delinq tot_coll_amt tot_cur_bal
0 63132 63132
open_acc_6m open_il_6m open_il_12m
779302 779302 779302
open_il_24m mths_since_rcnt_il total_bal_il
779302 779807 779302
il_util open_rv_12m open_rv_24m
781784 779302 779302
max_bal_bc all_util total_rev_hi_lim
779302 779302 63132
inq_fi total_cu_tl inq_last_12m
779302 779302 779302
annual_inc_merged dti_merged mths_since_delinq_cat
0 0 0
mths_since_last_record_cat mths_since_last_major_derog_cat
0 0
The columns revol_bal and revol_util contain only few NA values, those values can’t be replaced with 0, then we filter the values which are not NA
lc_data <- lc_data %>%
filter(!(is.na(revol_bal))) %>%
filter(!(is.na(revol_util)))
Let’s check which columns still have null values
names(which(colSums(is.na(lc_data)) > 0))
[1] "collections_12_mths_ex_med" "tot_coll_amt" "tot_cur_bal"
[4] "open_acc_6m" "open_il_6m" "open_il_12m"
[7] "open_il_24m" "mths_since_rcnt_il" "total_bal_il"
[10] "il_util" "open_rv_12m" "open_rv_24m"
[13] "max_bal_bc" "all_util" "total_rev_hi_lim"
[16] "inq_fi" "total_cu_tl" "inq_last_12m"
Replace null values with 0 where is possible
lc_data <-
lc_data %>%
mutate(open_acc_6m = ifelse(is.na(open_acc_6m) == TRUE, 0, open_acc_6m)) %>%
mutate(tot_cur_bal = ifelse(is.na(tot_cur_bal) == TRUE, 0, tot_cur_bal)) %>%
mutate(open_il_6m = ifelse(is.na(open_il_6m) == TRUE, 0, open_il_6m)) %>%
mutate(open_il_12m = ifelse(is.na(open_il_12m) == TRUE, 0, open_il_12m)) %>%
mutate(open_il_24m = ifelse(is.na(open_il_24m) == TRUE, 0, open_il_24m)) %>%
mutate(mths_since_rcnt_il = ifelse(is.na(mths_since_rcnt_il) == TRUE, 0, mths_since_rcnt_il)) %>%
mutate(total_bal_il = ifelse(is.na(total_bal_il) == TRUE, 0, total_bal_il)) %>%
mutate(il_util = ifelse(is.na(il_util) == TRUE, 0, il_util)) %>%
mutate(open_rv_12m = ifelse(is.na(open_rv_12m) == TRUE, 0, open_rv_12m)) %>%
mutate(total_rev_hi_lim = ifelse(is.na(total_rev_hi_lim) == TRUE, 0, total_rev_hi_lim)) %>%
mutate(max_bal_bc = ifelse(is.na(max_bal_bc) == TRUE, 0, max_bal_bc)) %>%
mutate(all_util = ifelse(is.na(all_util) == TRUE, 0, all_util)) %>%
mutate(inq_fi = ifelse(is.na(inq_fi) == TRUE, 0, inq_fi)) %>%
mutate(total_cu_tl = ifelse(is.na(total_cu_tl) == TRUE, 0, total_cu_tl)) %>%
mutate(inq_last_12m = ifelse(is.na(inq_last_12m) == TRUE, 0, inq_last_12m)) %>%
mutate(open_rv_24m = ifelse(is.na(open_rv_24m) == TRUE, 0, open_rv_24m)) %>%
mutate(tot_coll_amt = ifelse(is.na(tot_coll_amt)== TRUE,0, tot_coll_amt)) %>%
mutate(collections_12_mths_ex_med = ifelse(is.na(collections_12_mths_ex_med)== TRUE,0, collections_12_mths_ex_med))
earliest_cr_line contains the month the borrower’s earliest reported credit line was opened. Even if this date consists only on month and year, still there are too many unique values. We could transform the dates in to a numerical value, by converting them from date into Unix Time. This unit measures time by the number of seconds that have elapsed since 00:00:00 UTC on 1 January 1970. Since this column doesn’t contain the day number, we take as a reference the first day of the month.
lc_data <- lc_data %>%
filter(!(is.na(earliest_cr_line)))
# function to replace dates with unix time
to_unix_time <- function(date) {
tmp <- paste("01", date, sep="-")
return (as.numeric(as.POSIXct(tmp, format="%d-%b-%Y", tz="UTC")))
}
# map dates to unix time
lc_data$earliest_cr_line <- apply(lc_data, 1, function(row) to_unix_time(row["earliest_cr_line"]))
# standardize them
#lc_data$earliest_cr_line <- scale(lc_data$earliest_cr_line)
summary(lc_data)
loan_amnt term int_rate emp_length home_ownership
Min. : 500 Min. :1.0 Min. : 5.32 Min. : 1.00 Min. :1.000
1st Qu.: 8000 1st Qu.:1.0 1st Qu.: 9.99 1st Qu.: 3.00 1st Qu.:1.000
Median :13000 Median :1.0 Median :12.99 Median : 4.00 Median :2.000
Mean :14757 Mean :1.3 Mean :13.24 Mean : 5.11 Mean :1.901
3rd Qu.:20000 3rd Qu.:2.0 3rd Qu.:16.20 3rd Qu.: 7.00 3rd Qu.:3.000
Max. :35000 Max. :2.0 Max. :28.99 Max. :12.00 Max. :3.000
verification_status purpose addr_state delinq_2yrs earliest_cr_line
Min. :1.000 Min. : 1.000 Min. : 1.00 Min. : 0.0000 Min. :-820540800
1st Qu.:1.000 1st Qu.: 3.000 1st Qu.:10.00 1st Qu.: 0.0000 1st Qu.: 770428800
Median :2.000 Median : 3.000 Median :24.00 Median : 0.0000 Median : 936144000
Mean :2.027 Mean : 3.571 Mean :24.14 Mean : 0.3143 Mean : 889273164
3rd Qu.:3.000 3rd Qu.: 3.000 3rd Qu.:37.00 3rd Qu.: 0.0000 3rd Qu.:1051747200
Max. :3.000 Max. :14.000 Max. :51.00 Max. :39.0000 Max. :1351728000
inq_last_6mths open_acc pub_rec revol_bal revol_util
Min. : 0.0000 Min. : 1.00 Min. : 0.0000 Min. : 0 Min. : 0.00
1st Qu.: 0.0000 1st Qu.: 8.00 1st Qu.: 0.0000 1st Qu.: 6450 1st Qu.: 37.70
Median : 0.0000 Median :11.00 Median : 0.0000 Median : 11881 Median : 56.00
Mean : 0.6947 Mean :11.55 Mean : 0.1954 Mean : 16934 Mean : 55.05
3rd Qu.: 1.0000 3rd Qu.:14.00 3rd Qu.: 0.0000 3rd Qu.: 20844 3rd Qu.: 73.50
Max. :33.0000 Max. :90.00 Max. :63.0000 Max. :2904836 Max. :892.30
total_acc initial_list_status collections_12_mths_ex_med acc_now_delinq
Min. : 1.00 Min. :1.000 Min. : 0.00000 Min. : 0.000000
1st Qu.: 17.00 1st Qu.:1.000 1st Qu.: 0.00000 1st Qu.: 0.000000
Median : 24.00 Median :1.000 Median : 0.00000 Median : 0.000000
Mean : 25.27 Mean :1.485 Mean : 0.01448 Mean : 0.005026
3rd Qu.: 32.00 3rd Qu.:2.000 3rd Qu.: 0.00000 3rd Qu.: 0.000000
Max. :169.00 Max. :2.000 Max. :20.00000 Max. :14.000000
tot_coll_amt tot_cur_bal open_acc_6m open_il_6m open_il_12m
Min. : 0 Min. : 0 Min. : 0.00000 Min. : 0.00000 Min. : 0.00000
1st Qu.: 0 1st Qu.: 23195 1st Qu.: 0.00000 1st Qu.: 0.00000 1st Qu.: 0.00000
Median : 0 Median : 65402 Median : 0.00000 Median : 0.00000 Median : 0.00000
Mean : 210 Mean : 128461 Mean : 0.02641 Mean : 0.06982 Mean : 0.01816
3rd Qu.: 0 3rd Qu.: 195864 3rd Qu.: 0.00000 3rd Qu.: 0.00000 3rd Qu.: 0.00000
Max. :9152545 Max. :8000078 Max. :14.00000 Max. :33.00000 Max. :12.00000
open_il_24m mths_since_rcnt_il total_bal_il il_util open_rv_12m
Min. : 0.00000 Min. : 0.0000 Min. : 0 Min. : 0.000 Min. : 0.00000
1st Qu.: 0.00000 1st Qu.: 0.0000 1st Qu.: 0 1st Qu.: 0.000 1st Qu.: 0.00000
Median : 0.00000 Median : 0.0000 Median : 0 Median : 0.000 Median : 0.00000
Mean : 0.03991 Mean : 0.4918 Mean : 872 Mean : 1.489 Mean : 0.03316
3rd Qu.: 0.00000 3rd Qu.: 0.0000 3rd Qu.: 0 3rd Qu.: 0.000 3rd Qu.: 0.00000
Max. :19.00000 Max. :363.0000 Max. :878459 Max. :223.300 Max. :22.00000
open_rv_24m max_bal_bc all_util total_rev_hi_lim inq_fi
Min. : 0.00000 Min. : 0.0 Min. : 0.000 Min. : 0 Min. : 0.00000
1st Qu.: 0.00000 1st Qu.: 0.0 1st Qu.: 0.000 1st Qu.: 11700 1st Qu.: 0.00000
Median : 0.00000 Median : 0.0 Median : 0.000 Median : 21800 Median : 0.00000
Mean : 0.07114 Mean : 140.8 Mean : 1.456 Mean : 29564 Mean : 0.02262
3rd Qu.: 0.00000 3rd Qu.: 0.0 3rd Qu.: 0.000 3rd Qu.: 37900 3rd Qu.: 0.00000
Max. :43.00000 Max. :83047.0 Max. :151.400 Max. :9999999 Max. :16.00000
total_cu_tl inq_last_12m annual_inc_merged dti_merged mths_since_delinq_cat
Min. : 0.00000 Min. :-4.00000 Min. : 1896 Min. : 0.00 Min. :1.000
1st Qu.: 0.00000 1st Qu.: 0.00000 1st Qu.: 45000 1st Qu.:11.91 1st Qu.:3.000
Median : 0.00000 Median : 0.00000 Median : 65000 Median :17.66 Median :6.000
Mean : 0.03668 Mean : 0.04733 Mean : 75038 Mean :18.13 Mean :4.576
3rd Qu.: 0.00000 3rd Qu.: 0.00000 3rd Qu.: 90000 3rd Qu.:23.94 3rd Qu.:6.000
Max. :35.00000 Max. :32.00000 Max. :9500000 Max. :43.86 Max. :6.000
mths_since_last_record_cat mths_since_last_major_derog_cat
Min. :1.000 Min. :1.000
1st Qu.:6.000 1st Qu.:6.000
Median :6.000 Median :6.000
Mean :5.779 Mean :5.435
3rd Qu.:6.000 3rd Qu.:6.000
Max. :6.000 Max. :6.000
#round(cor(lc_data),2)
# TODO: (parte vecchia), split 80/20 e linear regression...
# Create indices for splitting (80% train, 20% test)
train_indices <- createDataPartition(lc_data$int_rate, p = 0.8, list = FALSE)
# Create training and testing datasets
train_data <- lc_data[train_indices, ]
test_data <- lc_data[-train_indices, ]
#### Linear Regression ####
#lm.fit <- lm(int_rate ~ ., data = train_data)
# TODO: check collinearity and multicollinearity
#vif(lm.fit) # there is multicollinearity
#cor(lc_data)
# Make predictions on training and testing data
#train_predictions <- predict(lm.fit, newdata = train_data)
#test_predictions <- predict(lm.fit, newdata = test_data)
# Evaluate model performance on training data
#train_rmse <- sqrt(mean((train_predictions - train_data$int_rate)^2))
#train_r_squared <- summary(lm.fit)$r.squared
# Evaluate model performance on testing data
#test_rmse <- sqrt(mean((test_predictions - test_data$int_rate)^2))
#test_r_squared <- summary(lm.fit, test_data)$r.squared
# Print evaluation metrics
#cat("Training RMSE:", train_rmse, "\n")
#cat("Training R-squared:", train_r_squared, "\n")
#rmse <- sqrt(mean(lm.fit$residuals^2))
#print(rmse)
#### Linear Regression ####
lm.fit <- lm(int_rate ~ ., data = train_data)
# Make predictions on the training and testing data
lm.train_predictions <- predict(lm.fit, newdata = train_data)
lm.test_predictions <- predict(lm.fit, newdata = test_data)
# Calculate Mean Squared Error (MSE) for training and testing
lm.train_mse <- mean((lm.train_predictions - train_data$int_rate)^2)
lm.test_mse <- mean((lm.test_predictions - test_data$int_rate)^2)
# Calculate Root Mean Squared Error (RMSE) for training and testing
lm.train_rmse <- sqrt(lm.train_mse)
lm.test_rmse <- sqrt(lm.test_mse)
# Calculate Mean Absolute Error (MAE) for training and testing
lm.train_mae <- mean(abs(lm.train_predictions - train_data$int_rate))
lm.test_mae <- mean(abs(lm.test_predictions - test_data$int_rate))
# Calculate R-squared (R²) for training and testing
lm.train_r2 <- 1 - (sum((train_data$int_rate - lm.train_predictions)^2) / sum((train_data$int_rate - mean(train_data$int_rate))^2))
lm.test_r2 <- 1 - (sum((test_data$int_rate - lm.test_predictions)^2) / sum((test_data$int_rate - mean(test_data$int_rate))^2))
# Display the metrics
cat("Training MSE:", lm.train_mse, "\n")
Training MSE: 10.69433
cat("Testing MSE:", lm.test_mse, "\n")
Testing MSE: 11.08025
cat("Training RMSE:", lm.train_rmse, "\n")
Training RMSE: 3.270218
cat("Testing RMSE:", lm.test_rmse, "\n")
Testing RMSE: 3.328701
cat("Training MAE:", lm.train_mae, "\n")
Training MAE: 2.591549
cat("Testing MAE:", lm.test_mae, "\n")
Testing MAE: 2.592027
cat("Training R-squared (R²):", lm.train_r2, "\n")
Training R-squared (R²): 0.4431432
cat("Testing R-squared (R²):", lm.test_r2, "\n")
Testing R-squared (R²): 0.4227827
#### Linear Regresion applying Cross Validation with k=2 to k=10 ####
# Assuming 'train_data' is your training data set
# Initialize lists to store models and their results
models <- list()
results <- data.frame()
# Define the number of folds for cross-validation
num_folds <- 10
folds <- createFolds(train_data$int_rate, k = num_folds, list = TRUE)
Lasso It standardizes data automatically
lasso.predictors_train <- model.matrix(int_rate ~ ., train_data)[,-1]
lasso.target_train <- train_data$int_rate
lasso.predictors_test <- model.matrix(int_rate ~ ., test_data)[,-1]
lasso.target_test <- test_data$int_rate
lasso.fit <- glmnet(lasso.predictors_train, lasso.target_train, alpha = 1)
dim(coef(lasso.fit))
[1] 41 70
# We have only 69 rows, because glmnet has a stop criterion, see help.
lasso.fit
Call: glmnet(x = lasso.predictors_train, y = lasso.target_train, alpha = 1)
Df %Dev Lambda
1 0 0.00 1.87700
2 1 3.11 1.71000
3 1 5.70 1.55800
4 1 7.85 1.42000
5 1 9.63 1.29400
6 1 11.11 1.17900
7 2 12.73 1.07400
8 3 15.01 0.97850
9 4 17.72 0.89160
10 4 20.19 0.81240
11 4 22.24 0.74020
12 6 24.54 0.67450
13 6 26.76 0.61450
14 7 28.69 0.55990
15 7 30.41 0.51020
16 9 32.15 0.46490
17 10 33.70 0.42360
18 10 35.04 0.38600
19 12 36.20 0.35170
20 13 37.34 0.32040
21 13 38.30 0.29200
22 14 39.11 0.26600
23 15 39.85 0.24240
24 15 40.47 0.22090
25 15 40.99 0.20120
26 16 41.42 0.18340
27 17 41.81 0.16710
28 17 42.13 0.15220
29 17 42.40 0.13870
30 17 42.62 0.12640
31 17 42.80 0.11520
32 19 42.97 0.10490
33 20 43.14 0.09560
34 20 43.28 0.08711
35 20 43.40 0.07937
36 21 43.52 0.07232
37 22 43.63 0.06590
38 23 43.72 0.06004
39 25 43.80 0.05471
40 27 43.88 0.04985
41 28 43.94 0.04542
42 31 44.00 0.04138
43 31 44.05 0.03771
44 31 44.09 0.03436
45 31 44.13 0.03131
46 31 44.16 0.02852
47 32 44.18 0.02599
48 33 44.21 0.02368
49 33 44.22 0.02158
50 33 44.24 0.01966
51 33 44.25 0.01791
52 33 44.26 0.01632
53 33 44.27 0.01487
54 35 44.28 0.01355
55 35 44.28 0.01235
56 35 44.29 0.01125
57 35 44.29 0.01025
58 36 44.30 0.00934
59 36 44.30 0.00851
60 36 44.30 0.00775
61 36 44.30 0.00707
62 36 44.30 0.00644
63 37 44.31 0.00587
64 37 44.31 0.00534
65 37 44.31 0.00487
66 37 44.31 0.00444
67 37 44.31 0.00404
68 37 44.31 0.00368
69 37 44.31 0.00336
70 37 44.31 0.00306
# We observe that some of the coefficients are set to zero (Df=0, %Dev=0)
plot(lasso.fit, label=TRUE)
# Also here we can see that some of the coefficients are set to zero.
# Make predictions on the training and testing data
lasso.train_predictions <- predict(lasso.fit, newdata = train_data, newx = lasso.predictors_train)
lasso.test_predictions <- predict(lasso.fit, newdata = test_data, newx = lasso.predictors_train)
# Calculate Mean Squared Error (MSE) for training and testing
lasso.train_mse <- mean((lasso.train_predictions - train_data$int_rate)^2)
lasso.test_mse <- mean((lasso.test_predictions - test_data$int_rate)^2)
Warning: longer object length is not a multiple of shorter object length
# Calculate Root Mean Squared Error (RMSE) for training and testing
lasso.train_rmse <- sqrt(lasso.train_mse)
lasso.test_rmse <- sqrt(lasso.test_mse)
# Calculate Mean Absolute Error (MAE) for training and testing
lasso.train_mae <- mean(abs(lasso.train_predictions - train_data$int_rate))
lasso.test_mae <- mean(abs(lasso.test_predictions - test_data$int_rate))
Warning: longer object length is not a multiple of shorter object length
# Calculate R-squared (R²) for training and testing
lasso.train_r2 <- 1 - (sum((train_data$int_rate - lasso.train_predictions)^2) / sum((train_data$int_rate - mean(train_data$int_rate))^2))
lasso.test_r2 <- 1 - (sum((test_data$int_rate - lasso.test_predictions)^2) / sum((test_data$int_rate - mean(test_data$int_rate))^2))
Warning: longer object length is not a multiple of shorter object length
# Display the metrics
cat("Training MSE:", lasso.train_mse, "\n")
Training MSE: 12.12513
cat("Testing MSE:", lasso.test_mse, "\n")
Testing MSE: 24.93444
cat("Training RMSE:", lasso.train_rmse, "\n")
Training RMSE: 3.482116
cat("Testing RMSE:", lasso.test_rmse, "\n")
Testing RMSE: 4.993439
cat("Training MAE:", lasso.train_mae, "\n")
Training MAE: 2.767999
cat("Testing MAE:", lasso.test_mae, "\n")
Testing MAE: 3.995769
cat("Training R-squared (R²):", lasso.train_r2, "\n")
Training R-squared (R²): -43.19514
cat("Testing R-squared (R²):", lasso.test_r2, "\n")
Testing R-squared (R²): -362.708
K fold
# Perform k-fold cross-validation
for(i in seq_along(folds)) {
# Split the data into training and testing for the current fold
train_indices <- folds[[i]]
test_indices <- setdiff(seq_len(nrow(train_data)), train_indices)
train_data_fold <- train_data[train_indices, ]
test_data_fold <- train_data[test_indices, ]
# Fit the model on the training fold
lm_model <- lm(int_rate ~ ., data = train_data_fold)
models[[i]] <- lm_model # Store the model
# Make predictions on the training and testing fold
train_predictions <- predict(lm_model, newdata = train_data_fold)
test_predictions <- predict(lm_model, newdata = test_data_fold)
# Calculate metrics for training fold
train_mse <- mean((train_predictions - train_data_fold$int_rate)^2)
train_rmse <- sqrt(train_mse)
train_mae <- mean(abs(train_predictions - train_data_fold$int_rate))
train_r2 <- summary(lm_model)$r.squared
# Calculate metrics for testing fold
test_mse <- mean((test_predictions - test_data_fold$int_rate)^2)
test_rmse <- sqrt(test_mse)
test_mae <- mean(abs(test_predictions - test_data_fold$int_rate))
test_r2 <- 1 - (sum((test_data_fold$int_rate - test_predictions)^2) / sum((test_data_fold$int_rate - mean(test_data_fold$int_rate))^2))
# Store metrics in the results dataframe
results <- rbind(results, data.frame(
Fold = i,
Train_MSE = train_mse, Test_MSE = test_mse,
Train_RMSE = train_rmse, Test_RMSE = test_rmse,
Train_MAE = train_mae, Test_MAE = test_mae,
Train_R2 = train_r2, Test_R2 = test_r2
))
}
# Display the models and their metrics
print(models)
[[1]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt
3.687e+00 3.469e-05
term emp_length
3.915e+00 9.005e-03
home_ownership verification_status
2.551e-01 7.508e-01
purpose addr_state
3.347e-01 6.467e-04
delinq_2yrs earliest_cr_line
3.082e-02 1.932e-09
inq_last_6mths open_acc
9.691e-01 6.753e-02
pub_rec revol_bal
3.904e-01 5.428e-06
revol_util total_acc
4.194e-02 -3.724e-02
initial_list_status collections_12_mths_ex_med
-1.049e+00 1.512e-01
acc_now_delinq tot_coll_amt
6.782e-01 3.681e-05
tot_cur_bal open_acc_6m
-1.095e-06 -1.567e-01
open_il_6m open_il_12m
-1.305e-01 7.125e-01
open_il_24m mths_since_rcnt_il
-8.877e-02 -3.827e-03
total_bal_il il_util
1.514e-06 3.403e-04
open_rv_12m open_rv_24m
2.705e-01 2.294e-02
max_bal_bc all_util
-7.473e-05 -5.008e-03
total_rev_hi_lim inq_fi
-1.764e-05 -1.048e-03
total_cu_tl inq_last_12m
-2.553e-02 8.400e-02
annual_inc_merged dti_merged
-3.718e-06 5.106e-02
mths_since_delinq_cat mths_since_last_record_cat
-2.081e-01 -1.273e-01
mths_since_last_major_derog_cat
-1.407e-01
[[2]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt
3.429e+00 3.113e-05
term emp_length
3.866e+00 1.831e-02
home_ownership verification_status
2.574e-01 7.300e-01
purpose addr_state
3.385e-01 2.182e-04
delinq_2yrs earliest_cr_line
2.873e-02 1.951e-09
inq_last_6mths open_acc
1.001e+00 5.913e-02
pub_rec revol_bal
4.440e-01 3.239e-06
revol_util total_acc
4.374e-02 -3.573e-02
initial_list_status collections_12_mths_ex_med
-1.000e+00 2.490e-01
acc_now_delinq tot_coll_amt
1.272e+00 1.774e-05
tot_cur_bal open_acc_6m
-1.300e-06 9.094e-02
open_il_6m open_il_12m
-1.316e-01 8.925e-01
open_il_24m mths_since_rcnt_il
-1.463e-01 -6.336e-03
total_bal_il il_util
2.455e-06 -7.798e-03
open_rv_12m open_rv_24m
2.190e-01 1.860e-02
max_bal_bc all_util
-7.492e-05 -5.555e-06
total_rev_hi_lim inq_fi
-1.524e-05 1.057e-01
total_cu_tl inq_last_12m
-3.456e-02 1.870e-02
annual_inc_merged dti_merged
-2.821e-06 5.502e-02
mths_since_delinq_cat mths_since_last_record_cat
-2.100e-01 -1.189e-01
mths_since_last_major_derog_cat
-1.397e-01
[[3]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt
3.477e+00 3.915e-05
term emp_length
3.859e+00 1.524e-02
home_ownership verification_status
2.942e-01 7.478e-01
purpose addr_state
3.451e-01 9.313e-04
delinq_2yrs earliest_cr_line
3.956e-02 1.908e-09
inq_last_6mths open_acc
9.963e-01 6.183e-02
pub_rec revol_bal
4.960e-01 8.155e-06
revol_util total_acc
4.161e-02 -3.297e-02
initial_list_status collections_12_mths_ex_med
-1.054e+00 2.626e-01
acc_now_delinq tot_coll_amt
1.548e+00 3.002e-05
tot_cur_bal open_acc_6m
-7.040e-07 -1.415e-01
open_il_6m open_il_12m
-1.334e-01 6.475e-01
open_il_24m mths_since_rcnt_il
-2.099e-02 -9.663e-03
total_bal_il il_util
1.714e-06 -6.237e-03
open_rv_12m open_rv_24m
2.508e-01 7.238e-02
max_bal_bc all_util
-3.408e-05 -5.609e-03
total_rev_hi_lim inq_fi
-1.721e-05 -1.224e-01
total_cu_tl inq_last_12m
4.731e-03 1.320e-01
annual_inc_merged dti_merged
-6.894e-06 4.595e-02
mths_since_delinq_cat mths_since_last_record_cat
-1.981e-01 -8.633e-02
mths_since_last_major_derog_cat
-1.485e-01
[[4]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt
3.522e+00 2.371e-05
term emp_length
3.944e+00 1.079e-02
home_ownership verification_status
2.374e-01 7.619e-01
purpose addr_state
3.457e-01 -5.854e-04
delinq_2yrs earliest_cr_line
5.499e-02 2.064e-09
inq_last_6mths open_acc
9.904e-01 4.485e-02
pub_rec revol_bal
4.673e-01 -5.328e-06
revol_util total_acc
4.785e-02 -3.256e-02
initial_list_status collections_12_mths_ex_med
-1.084e+00 4.324e-01
acc_now_delinq tot_coll_amt
1.448e+00 4.649e-05
tot_cur_bal open_acc_6m
-1.511e-06 4.101e-02
open_il_6m open_il_12m
-4.952e-02 8.524e-01
open_il_24m mths_since_rcnt_il
-1.789e-01 -1.213e-02
total_bal_il il_util
-2.769e-06 -8.909e-03
open_rv_12m open_rv_24m
1.033e-01 1.148e-01
max_bal_bc all_util
-9.269e-05 6.511e-04
total_rev_hi_lim inq_fi
-8.566e-07 2.049e-01
total_cu_tl inq_last_12m
-7.722e-02 5.632e-02
annual_inc_merged dti_merged
-4.368e-06 4.870e-02
mths_since_delinq_cat mths_since_last_record_cat
-2.042e-01 -1.447e-01
mths_since_last_major_derog_cat
-1.593e-01
[[5]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt
3.575e+00 3.425e-05
term emp_length
3.887e+00 1.826e-02
home_ownership verification_status
2.666e-01 7.308e-01
purpose addr_state
3.396e-01 -3.840e-04
delinq_2yrs earliest_cr_line
2.713e-02 1.918e-09
inq_last_6mths open_acc
9.760e-01 6.171e-02
pub_rec revol_bal
4.474e-01 5.601e-06
revol_util total_acc
4.242e-02 -3.458e-02
initial_list_status collections_12_mths_ex_med
-9.901e-01 3.209e-01
acc_now_delinq tot_coll_amt
1.486e+00 3.052e-05
tot_cur_bal open_acc_6m
-1.088e-06 5.196e-02
open_il_6m open_il_12m
-1.364e-01 6.768e-01
open_il_24m mths_since_rcnt_il
-5.342e-04 -3.752e-03
total_bal_il il_util
5.493e-06 -2.648e-03
open_rv_12m open_rv_24m
1.193e-01 6.411e-02
max_bal_bc all_util
-6.494e-05 -8.495e-03
total_rev_hi_lim inq_fi
-1.746e-05 -4.941e-02
total_cu_tl inq_last_12m
-8.903e-02 1.139e-01
annual_inc_merged dti_merged
-3.802e-06 5.315e-02
mths_since_delinq_cat mths_since_last_record_cat
-1.970e-01 -1.420e-01
mths_since_last_major_derog_cat
-1.398e-01
[[6]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt
4.326e+00 3.012e-05
term emp_length
3.919e+00 1.887e-02
home_ownership verification_status
2.406e-01 7.395e-01
purpose addr_state
3.281e-01 3.824e-04
delinq_2yrs earliest_cr_line
7.097e-02 1.826e-09
inq_last_6mths open_acc
9.754e-01 6.365e-02
pub_rec revol_bal
3.249e-01 4.268e-06
revol_util total_acc
4.345e-02 -3.399e-02
initial_list_status collections_12_mths_ex_med
-1.013e+00 3.503e-01
acc_now_delinq tot_coll_amt
1.700e+00 1.836e-05
tot_cur_bal open_acc_6m
-1.347e-06 9.756e-02
open_il_6m open_il_12m
-1.505e-01 6.353e-01
open_il_24m mths_since_rcnt_il
-1.506e-02 -9.094e-03
total_bal_il il_util
-9.415e-07 -3.528e-03
open_rv_12m open_rv_24m
6.864e-02 7.397e-02
max_bal_bc all_util
-5.028e-05 -3.241e-03
total_rev_hi_lim inq_fi
-1.496e-05 1.098e-01
total_cu_tl inq_last_12m
-5.422e-02 5.275e-02
annual_inc_merged dti_merged
-4.217e-06 4.987e-02
mths_since_delinq_cat mths_since_last_record_cat
-2.038e-01 -2.517e-01
mths_since_last_major_derog_cat
-1.247e-01
[[7]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt
4.029e+00 2.941e-05
term emp_length
3.926e+00 1.466e-02
home_ownership verification_status
2.442e-01 7.471e-01
purpose addr_state
3.362e-01 -4.177e-04
delinq_2yrs earliest_cr_line
1.666e-02 1.828e-09
inq_last_6mths open_acc
9.901e-01 6.751e-02
pub_rec revol_bal
3.511e-01 3.368e-06
revol_util total_acc
4.402e-02 -3.469e-02
initial_list_status collections_12_mths_ex_med
-1.026e+00 1.663e-01
acc_now_delinq tot_coll_amt
1.344e+00 1.963e-05
tot_cur_bal open_acc_6m
-1.108e-06 9.757e-02
open_il_6m open_il_12m
-2.140e-01 3.430e-01
open_il_24m mths_since_rcnt_il
4.755e-02 -7.888e-03
total_bal_il il_util
2.672e-06 -5.109e-04
open_rv_12m open_rv_24m
1.363e-01 3.419e-02
max_bal_bc all_util
-5.548e-05 -9.754e-04
total_rev_hi_lim inq_fi
-1.609e-05 9.087e-02
total_cu_tl inq_last_12m
-1.017e-01 7.059e-02
annual_inc_merged dti_merged
-3.906e-06 5.215e-02
mths_since_delinq_cat mths_since_last_record_cat
-1.943e-01 -1.885e-01
mths_since_last_major_derog_cat
-1.612e-01
[[8]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt
4.080e+00 3.560e-05
term emp_length
3.861e+00 1.314e-02
home_ownership verification_status
2.517e-01 7.451e-01
purpose addr_state
3.364e-01 -1.551e-04
delinq_2yrs earliest_cr_line
2.456e-02 1.867e-09
inq_last_6mths open_acc
9.789e-01 6.855e-02
pub_rec revol_bal
3.209e-01 5.071e-06
revol_util total_acc
4.202e-02 -3.402e-02
initial_list_status collections_12_mths_ex_med
-9.462e-01 3.700e-01
acc_now_delinq tot_coll_amt
1.496e+00 2.833e-05
tot_cur_bal open_acc_6m
-1.216e-06 -6.835e-03
open_il_6m open_il_12m
-1.769e-01 6.763e-01
open_il_24m mths_since_rcnt_il
-1.205e-01 -8.130e-03
total_bal_il il_util
3.297e-07 -3.268e-03
open_rv_12m open_rv_24m
3.139e-01 -2.944e-02
max_bal_bc all_util
-7.305e-05 6.118e-03
total_rev_hi_lim inq_fi
-1.750e-05 4.633e-02
total_cu_tl inq_last_12m
-7.276e-02 1.378e-02
annual_inc_merged dti_merged
-4.057e-06 5.053e-02
mths_since_delinq_cat mths_since_last_record_cat
-1.930e-01 -2.048e-01
mths_since_last_major_derog_cat
-1.555e-01
[[9]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt
4.132e+00 2.286e-05
term emp_length
3.931e+00 1.879e-02
home_ownership verification_status
2.717e-01 7.353e-01
purpose addr_state
3.408e-01 4.642e-04
delinq_2yrs earliest_cr_line
3.548e-02 1.961e-09
inq_last_6mths open_acc
9.972e-01 4.325e-02
pub_rec revol_bal
3.611e-01 -8.074e-06
revol_util total_acc
4.884e-02 -3.050e-02
initial_list_status collections_12_mths_ex_med
-1.135e+00 3.659e-01
acc_now_delinq tot_coll_amt
1.084e+00 2.830e-05
tot_cur_bal open_acc_6m
-1.599e-06 -1.537e-02
open_il_6m open_il_12m
-1.246e-01 5.945e-01
open_il_24m mths_since_rcnt_il
-2.310e-02 -8.046e-03
total_bal_il il_util
1.787e-06 -3.108e-03
open_rv_12m open_rv_24m
3.479e-01 -2.139e-03
max_bal_bc all_util
-7.060e-05 4.205e-04
total_rev_hi_lim inq_fi
-5.895e-07 1.947e-02
total_cu_tl inq_last_12m
-9.292e-02 3.775e-02
annual_inc_merged dti_merged
-3.756e-06 5.180e-02
mths_since_delinq_cat mths_since_last_record_cat
-1.927e-01 -2.594e-01
mths_since_last_major_derog_cat
-1.519e-01
[[10]]
Call:
lm(formula = int_rate ~ ., data = train_data_fold)
Coefficients:
(Intercept) loan_amnt
3.696e+00 3.226e-05
term emp_length
3.897e+00 1.263e-02
home_ownership verification_status
2.878e-01 7.393e-01
purpose addr_state
3.388e-01 1.123e-03
delinq_2yrs earliest_cr_line
2.915e-02 1.827e-09
inq_last_6mths open_acc
1.001e+00 6.172e-02
pub_rec revol_bal
3.963e-01 6.599e-06
revol_util total_acc
4.229e-02 -3.737e-02
initial_list_status collections_12_mths_ex_med
-1.002e+00 3.133e-01
acc_now_delinq tot_coll_amt
1.127e+00 2.331e-05
tot_cur_bal open_acc_6m
-8.802e-07 1.957e-01
open_il_6m open_il_12m
-1.312e-01 3.802e-01
open_il_24m mths_since_rcnt_il
-7.958e-03 -8.859e-03
total_bal_il il_util
2.294e-06 -5.317e-03
open_rv_12m open_rv_24m
1.104e-01 8.015e-02
max_bal_bc all_util
-6.980e-05 1.842e-03
total_rev_hi_lim inq_fi
-1.754e-05 -2.145e-02
total_cu_tl inq_last_12m
-6.802e-02 4.283e-02
annual_inc_merged dti_merged
-2.587e-06 5.252e-02
mths_since_delinq_cat mths_since_last_record_cat
-2.019e-01 -1.620e-01
mths_since_last_major_derog_cat
-1.377e-01
print(results)
NA
Decision Tree
#### Decision Trees ####
# Error in tree: "factor predictors must have at most 32 levels" is thrown.
# Basically, it becomes computationally expensive to create so many splits in your data, since you are selecting the best split out of all 2^32 (approx) possible splits.
# Fit a decision tree model on the training data
#tm <- tree(int_rate ~ ., data = train_data)
# Make predictions on the training and testing data
#tm.train_predictions <- predict(tm, newdata = train_data)
#tm.test_predictions <- predict(tm, newdata = test_data)
# Calculate Mean Squared Error (MSE) for training and testing
#tm.train_mse <- mean((tm.train_predictions - train_data$int_rate)^2)
#tm.test_mse <- mean((tm.test_predictions - test_data$int_rate)^2)
# Calculate Root Mean Squared Error (RMSE) for training and testing
#tm.train_rmse <- sqrt(tm.train_mse)
#tm.test_rmse <- sqrt(tm.test_mse)
# Calculate Mean Absolute Error (MAE) for training and testing
#tm.train_mae <- mean(abs(tm.train_predictions - train_data$int_rate))
#tm.test_mae <- mean(abs(tm.test_predictions - test_data$int_rate))
# Calculate R-squared (R²) for training and testing
#tm.train_r2 <- 1 - (sum((train_data$int_rate - tm.train_predictions)^2) / sum((train_data$int_rate - mean(train_data$int_rate))^2))
#tm.test_r2 <- 1 - (sum((test_data$int_rate - tm.test_predictions)^2) / sum((test_data$int_rate - mean(test_data$int_rate))^2))
# Display the metrics
#cat("Training MSE:", tm.train_mse, "\n")
#cat("Testing MSE:", tm.test_mse, "\n")
#cat("Training RMSE:", tm.train_rmse, "\n")
#cat("Testing RMSE:", tm.test_rmse, "\n")
#cat("Training MAE:", tm.train_mae, "\n")
#cat("Testing MAE:", tm.test_mae, "\n")
#cat("Training R-squared (R²):", tm.train_r2, "\n")
#cat("Testing R-squared (R²):", tm.test_r2, "\n")
Random Forest
#### Random Forest ####
# Train a Random Forest model
rf <- ranger(formula = int_rate ~ ., data = train_data, num.trees = 500, verbose=TRUE, importance = "impurity", oob.error = TRUE)
Growing trees.. Progress: 11%. Estimated remaining time: 4 minutes, 0 seconds.
Growing trees.. Progress: 24%. Estimated remaining time: 3 minutes, 17 seconds.
Growing trees.. Progress: 35%. Estimated remaining time: 2 minutes, 54 seconds.
Growing trees.. Progress: 47%. Estimated remaining time: 2 minutes, 22 seconds.
Growing trees.. Progress: 59%. Estimated remaining time: 1 minute, 47 seconds.
Growing trees.. Progress: 72%. Estimated remaining time: 1 minute, 13 seconds.
Growing trees.. Progress: 84%. Estimated remaining time: 41 seconds.
Growing trees.. Progress: 96%. Estimated remaining time: 10 seconds.
# Print the model summary
print("Random Forest Model Summary:")
[1] "Random Forest Model Summary:"
print(rf)
Ranger result
Call:
ranger(formula = int_rate ~ ., data = train_data, num.trees = 500, verbose = TRUE, importance = "impurity", oob.error = TRUE)
Type: Regression
Number of trees: 500
Sample size: 638392
Number of independent variables: 40
Mtry: 6
Target node size: 5
Variable importance mode: impurity
Splitrule: variance
OOB prediction error (MSE): 8.744647
R squared (OOB): 0.5446644
# Make predictions on the training and testing data
rf.train_predictions <- predict(rf, data = train_data)
Predicting.. Progress: 88%. Estimated remaining time: 4 seconds.
rf.test_predictions <- predict(rf, data = test_data)
# Calculate Mean Squared Error (MSE) for training and testing
rf.train_mse <- mean((rf.train_predictions$predictions - train_data$int_rate)^2)
rf.test_mse <- mean((rf.test_predictions$predictions - test_data$int_rate)^2)
# Calculate Root Mean Squared Error (RMSE) for training and testing
rf.train_rmse <- sqrt(rf.train_mse)
rf.test_rmse <- sqrt(rf.test_mse)
# Calculate Mean Absolute Error (MAE) for training and testing
rf.train_mae <- mean(abs(rf.train_predictions$predictions - train_data$int_rate))
rf.test_mae <- mean(abs(rf.test_predictions$predictions - test_data$int_rate))
# Calculate R-squared (R²) for training and testing
rf.train_r2 <- 1 - (sum((train_data$int_rate - rf.train_predictions$predictions)^2) / sum((train_data$int_rate - mean(train_data$int_rate))^2))
rf.test_r2 <- 1 - (sum((test_data$int_rate - rf.test_predictions$predictions)^2) / sum((test_data$int_rate - mean(test_data$int_rate))^2))
# Display the metrics
cat("Training MSE:", rf.train_mse, "\n")
Training MSE: 2.066856
cat("Testing MSE:", rf.test_mse, "\n")
Testing MSE: 8.69323
cat("Training RMSE:", rf.train_rmse, "\n")
Training RMSE: 1.437656
cat("Testing RMSE:", rf.test_rmse, "\n")
Testing RMSE: 2.948428
cat("Training MAE:", rf.train_mae, "\n")
Training MAE: 1.130191
cat("Testing MAE:", rf.test_mae, "\n")
Testing MAE: 2.331673
cat("Training R-squared (R²):", rf.train_r2, "\n")
Training R-squared (R²): 0.8923782
cat("Testing R-squared (R²):", rf.test_r2, "\n")
Testing R-squared (R²): 0.5471326
#rf <- randomForest(int_rate~., data=train_data, ntree = 5, mtry = 3)
#bag.boston=randomForest(medv~.,data=Boston,subset=train, mtry=13,importance =TRUE)
#print(rf)
# Set the number of cores you want to use
#num_cores <- 6 # Adjust this number based on your system's capabilities
# Register parallel backend
#cl <- makeCluster(num_cores)
#registerDoParallel(cl)
# Assuming 'lc_data' is your dataset
#rf_model <- foreach(ntree = rep(100, num_cores), .packages = 'randomForest') %dopar% {
# randomForest(int_rate ~ ., data = lc_data, ntree = ntree, mtry = sqrt(ncol(lc_data)))
#}
# After training, stop the cluster to release the cores:
#stopCluster(cl)
Boosting
#### Boosting ####
# Define the target variable for training and testing
xgb.y_train <- train_data$int_rate
xgb.y_test <- test_data$int_rate # Use test_data for testing
# Define the feature matrix for training and testing (exclude the target variable)
xgb.X_train <- train_data[, -which(names(train_data) == 'int_rate')]
xgb.X_test <- test_data[, -which(names(test_data) == 'int_rate')] # Use test_data for testing
# Fit a gradient boosting regression model using xgboost
xgb <- xgboost(
data = as.matrix(xgb.X_train),
label = xgb.y_train,
nrounds = 100,
verbose = 0
)
# Make predictions on the training and testing data
xgb.train_predictions <- predict(xgb, newdata = as.matrix(xgb.X_train))
xgb.test_predictions <- predict(xgb, newdata = as.matrix(xgb.X_test))
# Calculate Mean Squared Error (MSE) for training and testing
xgb.train_mse <- mean((xgb.train_predictions - xgb.y_train)^2)
xgb.test_mse <- mean((xgb.test_predictions - xgb.y_test)^2)
# Calculate Root Mean Squared Error (RMSE) for training and testing
xgb.train_rmse <- sqrt(xgb.train_mse)
xgb.test_rmse <- sqrt(xgb.test_mse)
# Calculate Mean Absolute Error (MAE) for training and testing
xgb.train_mae <- mean(abs(xgb.train_predictions - xgb.y_train))
xgb.test_mae <- mean(abs(xgb.test_predictions - xgb.y_test))
# Calculate R-squared (R²) for training and testing
xgb.train_r2 <- 1 - (sum((xgb.y_train - xgb.train_predictions)^2) / sum((xgb.y_train - mean(xgb.y_train))^2))
xgb.test_r2 <- 1 - (sum((xgb.y_test - xgb.test_predictions)^2) / sum((xgb.y_test - mean(xgb.y_test))^2))
# Display the metrics
cat("Training MSE:", xgb.train_mse, "\n")
Training MSE: 7.70773
cat("Testing MSE:", xgb.test_mse, "\n")
Testing MSE: 8.007011
cat("Training RMSE:", xgb.train_rmse, "\n")
Training RMSE: 2.77628
cat("Testing RMSE:", xgb.test_rmse, "\n")
Testing RMSE: 2.829666
cat("Training MAE:", xgb.train_mae, "\n")
Training MAE: 2.179231
cat("Testing MAE:", xgb.test_mae, "\n")
Testing MAE: 2.219719
cat("Training R-squared (R²):", xgb.train_r2, "\n")
Training R-squared (R²): 0.5986562
cat("Testing R-squared (R²):", xgb.test_r2, "\n")
Testing R-squared (R²): 0.5828808
Following, a scatter plot of actual vs predicted training values for each model is plot. This plot helps us visualize how well each model’s predictions align with the actual data points.
# Create a scatter plot function
create_scatter_plot <- function(actual_values, predicted_values, model_name) {
model_comparison_data <- data.frame(
Actual = actual_values,
Predicted = predicted_values
)
scatter_plot <- ggplot(model_comparison_data, aes(x = Actual, y = Predicted)) +
geom_point() +
geom_abline(intercept = 0, slope = 1, linetype = "dashed", color = "red") + # Add a diagonal reference line
labs(x = "Actual Training Values", y = "Predicted Training Values", title = model_name) +
theme_minimal() +
ylim(-50, 50)
return(scatter_plot)
}
# Create scatter plots for each model
lm_scatter_plot <- create_scatter_plot(
actual_values = train_data$int_rate,
predicted_values = lm.train_predictions,
model_name = "Linear Regression"
)
rf_scatter_plot <- create_scatter_plot(
actual_values = train_data$int_rate,
predicted_values = rf.train_predictions$predictions,
model_name = "Random Forest"
)
xgb_scatter_plot <- create_scatter_plot(
actual_values = xgb.y_train,
predicted_values = xgb.train_predictions,
model_name = "XGBoost"
)
# Display the scatter plots separately
print(lm_scatter_plot)
print(rf_scatter_plot)
print(xgb_scatter_plot)
Following, a scatter plot of actual vs predicted testing values for each model is plot. This plot helps us visualize how well each model’s predictions align with the actual data points.
# Create a scatter plot function
create_scatter_plot <- function(actual_values, predicted_values, model_name) {
model_comparison_data <- data.frame(
Actual = actual_values,
Predicted = predicted_values
)
scatter_plot <- ggplot(model_comparison_data, aes(x = Actual, y = Predicted)) +
geom_point() +
geom_abline(intercept = 0, slope = 1, linetype = "dashed", color = "red") + # Add a diagonal reference line
labs(x = "Actual Testing Values", y = "Predicted Testing Values", title = model_name) +
theme_minimal() +
ylim(-50, 50) +
xlim(0, 40)
return(scatter_plot)
}
# Create scatter plots for each model
lm_scatter_plot <- create_scatter_plot(
actual_values = test_data$int_rate,
predicted_values = lm.test_predictions,
model_name = "Linear Regression"
)
rf_scatter_plot <- create_scatter_plot(
actual_values = test_data$int_rate,
predicted_values = rf.test_predictions$predictions,
model_name = "Random Forest"
)
xgb_scatter_plot <- create_scatter_plot(
actual_values = xgb.y_test,
predicted_values = xgb.test_predictions,
model_name = "XGBoost"
)
# Display the scatter plots separately
print(lm_scatter_plot)
print(rf_scatter_plot)
print(xgb_scatter_plot)
Residual plots can help identify patterns in prediction errors and assess whether the assumptions of linear regression (if applicable) are met.
# Create a residual plot function
create_residual_plot <- function(actual_values, predicted_values, model_name) {
residuals <- actual_values - predicted_values
residual_data <- data.frame(
Predicted = predicted_values,
Residuals = residuals
)
residual_plot <- ggplot(residual_data, aes(x = Predicted, y = Residuals)) +
geom_point() +
geom_hline(yintercept = 0, linetype = "dashed", color = "red") + # Red horizontal reference line
labs(x = "Predicted Values", y = "Residuals", title = paste("Residual Plot -", model_name)) +
theme_minimal() +
ylim(-30, 30) +
xlim(0, 40)
return(residual_plot)
}
# Create residual plots for each model
lm_residual_plot <- create_residual_plot(
actual_values = train_data$int_rate,
predicted_values = lm.train_predictions,
model_name = "Linear Regression"
)
rf_residual_plot <- create_residual_plot(
actual_values = train_data$int_rate,
predicted_values = rf.train_predictions$predictions,
model_name = "Random Forest"
)
xgb_residual_plot <- create_residual_plot(
actual_values = xgb.y_train,
predicted_values = xgb.train_predictions,
model_name = "XGBoost"
)
# Display the residual plots separately
print(lm_residual_plot)
print(rf_residual_plot)
print(xgb_residual_plot)
From the plots above we can clearly see that:
This visualization can help you compare the distribution of prediction errors across models.
# Create a density plot function for residuals
create_residual_density_plot <- function(actual_values, predicted_values, model_name) {
residuals <- actual_values - predicted_values
residual_data <- data.frame(Residuals = residuals)
density_plot <- ggplot(residual_data, aes(x = Residuals)) +
geom_density(fill = "skyblue", color = "black", alpha = 0.7) +
labs(x = "Residuals", y = "Density", title = paste("Residual Density Plot -", model_name)) +
theme_minimal() +
xlim(-30,30) +
ylim(0, 0.35)
return(density_plot)
}
# Create density plots for residuals for each model
lm_residual_density_plot <- create_residual_density_plot(
actual_values = train_data$int_rate,
predicted_values = lm.train_predictions,
model_name = "Linear Regression"
)
rf_residual_density_plot <- create_residual_density_plot(
actual_values = train_data$int_rate,
predicted_values = rf.train_predictions$predictions,
model_name = "Random Forest"
)
xgb_residual_density_plot <- create_residual_density_plot(
actual_values = xgb.y_train,
predicted_values = xgb.train_predictions,
model_name = "XGBoost"
)
# Display the density plots separately
print(lm_residual_density_plot)
print(rf_residual_density_plot)
print(xgb_residual_density_plot)
This visualization can help you compare the distribution of prediction errors across models through histograms.
# Create a histogram plot function for residuals with a red density curve
create_residual_histogram_plot <- function(actual_values, predicted_values, model_name) {
residuals <- actual_values - predicted_values
residual_data <- data.frame(Residuals = residuals)
histogram_plot <- ggplot(residual_data, aes(x = Residuals)) +
geom_histogram(aes(y = after_stat(density)), bins = 30, fill = "skyblue", color = "black", alpha = 0.7) + # Use density on the y-axis for the histogram
geom_density(color = "red", linewidth = 1.5) + # Add the density plot in red
labs(x = "Residuals", y = "Density", title = paste("Residual Histogram Plot with Density Curve -", model_name)) +
theme_minimal() +
xlim(-20,20) +
ylim(0, 0.3)
return(histogram_plot)
}
# Create histogram plots for residuals for each model
lm_residual_histogram_plot <- create_residual_histogram_plot(
actual_values = train_data$int_rate,
predicted_values = lm.train_predictions,
model_name = "Linear Regression"
)
rf_residual_histogram_plot <- create_residual_histogram_plot(
actual_values = train_data$int_rate,
predicted_values = rf.train_predictions$predictions,
model_name = "Random Forest"
)
xgb_residual_histogram_plot <- create_residual_histogram_plot(
actual_values = xgb.y_train,
predicted_values = xgb.train_predictions,
model_name = "XGBoost"
)
# Display the histogram plots separately
print(lm_residual_histogram_plot)
print(rf_residual_histogram_plot)
print(xgb_residual_histogram_plot)
For each model a bar chart that displays the R-squared (coefficient of determination) values is created. R-squared measures the proportion of variance in the target variable explained by the model. Higher R-squared values indicate better model fit.
# Create a data frame with R-squared values for each model
model_names <- c("Linear Regression", "Random Forest", "XGBoost")
r_squared_values_train <- c(
lm.train_r2,
rf.train_r2,
xgb.train_r2
)
r_squared_values_test <- c(
lm.test_r2,
rf.test_r2,
xgb.test_r2
)
r_squared_data_train <- data.frame(Model = factor(model_names),
R_squared = r_squared_values_train)
r_squared_data_test <- data.frame(Model = factor(model_names),
R_squared = r_squared_values_test)
# Create the R-squared comparison bar chart
r_squared_bar_chart_train <- ggplot(r_squared_data_train, aes(x = Model, y = R_squared, fill = Model)) +
geom_bar(stat = "identity") +
labs(x = "Model", y = "R-squared (R²)", title = "R-squared Comparison") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
ylim(0,1)
r_squared_bar_chart_test <- ggplot(r_squared_data_test, aes(x = Model, y = R_squared, fill = Model)) +
geom_bar(stat = "identity") +
labs(x = "Model", y = "R-squared (R²)", title = "R-squared Comparison") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
ylim(0,1)
# Display the R-squared comparison bar chart
print(r_squared_bar_chart_train)
print(r_squared_bar_chart_test)
A bar chart that compares the MAE or RMSE values, is generated for each model. These metrics quantify the average prediction errors of each model, and lower values are preferred.
# Create a data frame with MAE and RMSE values for each model
model_names <- c("Linear Regression", "Random Forest", "XGBoost","Linear Regression", "Random Forest", "XGBoost")
error_values_train <- c(
lm.train_mae,
rf.train_mae,
xgb.train_mae,
lm.train_rmse,
rf.train_rmse,
xgb.train_rmse
)
error_values_test <- c(
lm.test_mae,
rf.test_mae,
xgb.test_mae,
lm.test_rmse,
rf.test_rmse,
xgb.test_rmse
)
error_type <- c(
"MAE", "MAE", "MAE","RMSE","RMSE","RMSE"
)
model_errors_train <- data.frame(Model = factor(model_names, levels = c("Linear Regression", "Random Forest", "XGBoost")),
Error = error_values_train, Type = error_type)
model_errors_test <- data.frame(Model = factor(model_names, levels = c("Linear Regression", "Random Forest", "XGBoost")),
Error = error_values_test, Type = error_type)
# Create the MAE or RMSE comparison bar chart
error_bar_chart_train <- ggplot(model_errors_train, aes(x = Model, y = Error, fill = Type)) +
geom_bar(stat = "identity", position = "dodge") +
labs(x = "Model", y = "Error Value", title = "Training MAE and RMSE Comparison") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
ylim(0, 4)
error_bar_chart_test <- ggplot(model_errors_test, aes(x = Model, y = Error, fill = Type)) +
geom_bar(stat = "identity", position = "dodge") +
labs(x = "Model", y = "Error Value", title = "Testing MAE and RMSE Comparison") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
ylim(0, 4)
# Display the MAE and RMSE comparison bar chart
print(error_bar_chart_train)
print(error_bar_chart_test)
#### Random Forest Feature Importance Plot ####
v1 <- vip(rf, title = "Ranger", num_features = 20)
plot(v1)
Learning curve using RMSE and R^2:
# TODO: change the x-axes
# Create a data frame with RMSE and R-squared values for each model and sample size
model_names <- c("Linear Regression", "Random Forest", "XGBoost")
sample_sizes <- seq(10, nrow(train_data), by = 10) # Adjust the sample sizes as needed
# Create data frames with RMSE and R-squared values for each model
rmse_data <- data.frame(
Model = rep(model_names, each = length(sample_sizes)),
Sample_Size = rep(sample_sizes, times = length(model_names)),
RMSE = c(
lm.train_rmse, rf.train_rmse, xgb.train_rmse
)
)
r_squared_data <- data.frame(
Model = rep(model_names, each = length(sample_sizes)),
Sample_Size = rep(sample_sizes, times = length(model_names)),
R_squared = c(
lm.train_r2, rf.train_r2, xgb.train_r2
)
)
# Create RMSE learning curve
rmse_curve <- ggplot(rmse_data, aes(x = Sample_Size, y = RMSE, color = Model)) +
geom_line() +
labs(x = "Sample Size", y = "RMSE", title = "RMSE Learning Curve") +
theme_minimal()
# Create R-squared learning curve
r_squared_curve <- ggplot(r_squared_data, aes(x = Sample_Size, y = R_squared, color = Model)) +
geom_line() +
labs(x = "Sample Size", y = "R-squared", title = "R-squared Learning Curve") +
theme_minimal()
# Display the RMSE and R-squared learning curves
print(rmse_curve)
print(r_squared_curve)
Add a new chunk by clicking the Insert Chunk button on the toolbar or by pressing Ctrl+Alt+I.
When you save the notebook, an HTML file containing the code and output will be saved alongside it (click the Preview button or press Ctrl+Shift+K to preview the HTML file).
The preview shows you a rendered HTML copy of the contents of the editor. Consequently, unlike Knit, Preview does not run any R code chunks. Instead, the output of the chunk when it was last run in the editor is displayed.